package com.demo.config.handler;

import com.demo.common.constant.JWTConstants;
import com.demo.common.model.LoginResult;
import com.demo.common.model.R;
import com.demo.common.model.SecurityUser;
import com.demo.common.utils.JWTUtils;
import com.demo.common.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;

/*
    登录成功处理器
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {

        // 从认证对象中获取安全认证用户对象消息
        SecurityUser securityUser =(SecurityUser) authentication.getPrincipal();
        // 生成一个令牌 token
        String jwt_token = JWTUtils.createJWT(securityUser);
        // 将令牌 token 存入redis
        redisTemplate.opsForValue().set(JWTConstants.JWT_REDIS_KEY_PREFIX+jwt_token,"",
                Duration.ofMinutes(JWTConstants.JWT_REDIS_EXPIRE_IN));
        // 获取”记住我“参数
        boolean rememberMe = Boolean.parseBoolean(request.getParameter("rememberMe"));
        // 判断是否选中
        if (rememberMe){
            // 已选择 ”记住我“ 将令牌 token 存放时间设置为30天
            redisTemplate.opsForValue().set(JWTConstants.JWT_REDIS_KEY_PREFIX+jwt_token,"",
                    Duration.ofMinutes(JWTConstants.JWT_REDIS_REMEMBER_EXPIRE_IN));
        }
        // 响应数据
//        ResponseUtils.writeJson(response, R.OK(jwt_token));
        ResponseUtils.writeJson(response, R.OK(new LoginResult(jwt_token,securityUser.getPermissionList())));
    }
}
